package com.sky.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Blog;
import com.sky.domain.Type;
import com.sky.domain.User;
import com.sky.service.BlogService;
import com.sky.service.TagService;
import com.sky.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private BlogService blogService;

    // 封装标签和分类
    public void setTypeAndTag(Model model){
        model.addAttribute("tags",tagService.getAllTag());
        model.addAttribute("types",typeService.getAllType());
    }

    // 展示所有的blog 分页查询
    @GetMapping("/blogs")
    public String blogs(@RequestParam( value = "pageNum",defaultValue = "1") Integer pageNum,
                        Model model){
        PageHelper.startPage(pageNum,5);
        List<Type> typeList = typeService.getAllType();
        List<Blog> blogList = blogService.getAllBlog();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("types",typeList);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/blogs";
    }

    // 跳转添加博客
    @GetMapping("/blogs/input")
    public String input(Model model){
        model.addAttribute("blog",new Blog());
        setTypeAndTag(model);
        return "admin/blogs_input";
    }

    // 跳转更新博客
    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable("id") Long id,Model model){
        Blog blog = blogService.getBlogById(id);
        model.addAttribute("blog",blog);
        setTypeAndTag(model);
        return "admin/blogs_input";
    }

    // 筛选添加或者更新操作
    @PostMapping("/blogs")
    public String post(Blog blog, HttpSession session,HttpServletRequest request,
                       @RequestParam("file")  MultipartFile multipartFile,
                       RedirectAttributes attributes) throws IOException {
        User user = (User)session.getAttribute("user");
        blog.setUser(user);
        blog.setUserId(user.getId());
        // 将标签名称返回
        blog.setTags(tagService.getTagByString(blog.getTagIds()));
        // 将文件保存
        String file_name = upload(multipartFile,request);
        // 数据库中保存文件名字
        blog.setFirstPicture(file_name);

        System.out.println(blog);
        if (blog.getId()==null){
            // 添加操作
            blogService.saveBlog(blog);
            attributes.addFlashAttribute("message","添加成功！");
        }else{
            // 更新操作
            blogService.updateBlog(blog);
            attributes.addFlashAttribute("message","更新成功！");
        }
        return "redirect:/admin/blogs";
    }

    //上传图片地址
    public String upload(MultipartFile pictureFile, HttpServletRequest request) throws IOException {
//      获取提交文件名称
        String filename = pictureFile.getOriginalFilename();
//      定个时间戳，避免名称重复
        String newName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + filename;
//      定义上传文件存放的路径
        String filePath = "E://upload/";
        //写入文件
        File saveFile = new File(filePath, newName);
        pictureFile.transferTo(saveFile);//文件保存
        return filePath;
    }

    // 删除操作
    @GetMapping("/blogs/{id}/delete")
    public String deleteBlog(@PathVariable("id") Long id,
                             RedirectAttributes attributes){
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message","删除成功！");
        return "redirect:/admin/blogs";
    }

    // 搜索操作
    @PostMapping("/blogs/search")
    public String searchBlogs(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                              Blog blog,Model model) {
        //分页查询
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogList = blogService.searchAllBlog(blog);
        //分页结果对象
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("message", "查询成功");
        setTypeAndTag(model);
        return "admin/blogs";
    }
}
